package com.acme.iolab.serialization.serializers;


import com.acme.iolab.serialization.SensorData;
import com.google.protobuf.InvalidProtocolBufferException;

public class ProtobufSerializer implements Serializer {

    SensorDataProto.SensorData.Builder builder = SensorDataProto.SensorData.newBuilder();

    @Override
    public Object serialize(Object object) {
        SensorData sensorData = (SensorData) object;
        builder.setElevation(sensorData.getDepth());
        builder.setLatitude(sensorData.getLatitude());
        builder.setLongitude(sensorData.getLongitude());
        builder.setTemperature(sensorData.getTemperature());
        return builder.build().toByteArray();
    }

    @Override
    public Object deSerialize(Object object) {
        try {
            SensorDataProto.SensorData pSensorData = SensorDataProto.SensorData.parseFrom((byte[]) object);
            SensorData sensorData = new SensorData();
            sensorData.setDepth(pSensorData.getElevation());
            sensorData.setLatitude(pSensorData.getLatitude());
            sensorData.setLongitude(pSensorData.getLongitude());
            sensorData.setTemperature(pSensorData.getTemperature());
            return sensorData;
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        return null;
    }
}
